<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    零散的MySQL基础总是记不住？看这一篇就够了.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-mysql/零散的MySQL基础总是记不住？看这一篇就够了"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  零散的MySQL基础总是记不住？看这一篇就够了.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/mysql/%E9%9B%B6%E6%95%A3%E7%9A%84MySQL%E5%9F%BA%E7%A1%80%E6%80%BB%E6%98%AF%E8%AE%B0%E4%B8%8D%E4%BD%8F%EF%BC%9F%E7%9C%8B%E8%BF%99%E4%B8%80%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/mysql/">mysql</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.6k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">11 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="零散的MySQL基础总是记不住？看这一篇就够了！"><a href="#零散的MySQL基础总是记不住？看这一篇就够了！" class="headerlink" title="零散的MySQL基础总是记不住？看这一篇就够了！"></a>零散的MySQL基础总是记不住？看这一篇就够了！</h2><p>Sicimike <a href="javascript:void(0);">Java团长</a> <em>3天前</em></p>
<h2 id=""><a href="#" class="headerlink" title=""></a><img src="http://iubest.gitee.io/pic/640-1601002104254.webp" alt="img"></h2><h2 id="来源：http-suo-im-5Oa04O"><a href="#来源：http-suo-im-5Oa04O" class="headerlink" title="来源：http://suo.im/5Oa04O"></a>来源：<a target="_blank" rel="noopener" href="http://suo.im/5Oa04O">http://suo.im/5Oa04O</a></h2><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>在日常开发中，一些不常用且又比较基础的知识，过了一段时间之后，总是容易忘记或者变得有点模棱两可。本篇主要记录一些关于MySQL数据库比较基础的知识，以便日后快速查看。</p>
<h2 id="SQL命令"><a href="#SQL命令" class="headerlink" title="SQL命令"></a>SQL命令</h2><p>SQL命令分可以分为四组：DDL、DML、DCL和TCL。四组中包含的命令分别如下<br><img src="http://iubest.gitee.io/pic/640-1601002104334.webp" alt="img"><br>（图片来源见水印）</p>
<h3 id="DDL"><a href="#DDL" class="headerlink" title="DDL"></a>DDL</h3><p>DDL是数据定义语言（Data Definition Language）的简称，它处理数据库schemas和描述数据应如何驻留在数据库中。</p>
<ul>
<li><code>CREATE</code>：创建数据库及其对象（如表，索引，视图，存储过程，函数和触发器）</li>
<li><code>ALTER</code>：改变现有数据库的结构</li>
<li><code>DROP</code>：从数据库中删除对象</li>
<li><code>TRUNCATE</code>：从表中删除所有记录，包括为记录分配的所有空间都将被删除</li>
<li><code>COMMENT</code>：添加注释</li>
<li><code>RENAME</code>：重命名对象</li>
</ul>
<p>常用命令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"># 建表</span><br><span class="line">CREATE TABLE sicimike  (</span><br><span class="line">  id int(4) primary key auto_increment COMMENT &#39;主键ID&#39;,</span><br><span class="line">  name varchar(10) unique,</span><br><span class="line">  age int(3) default 0,</span><br><span class="line">  identity_card varchar(18)</span><br><span class="line">  # PRIMARY KEY (id) &#x2F;&#x2F; 也可以通过这种方式设置主键</span><br><span class="line">  # UNIQUE KEY (name) &#x2F;&#x2F; 也可以通过这种方式设置唯一键</span><br><span class="line">  # key&#x2F;index (identity_card, col1...) &#x2F;&#x2F; 也可以通过这种方式创建索引</span><br><span class="line">) ENGINE &#x3D; InnoDB;</span><br><span class="line"></span><br><span class="line"># 设置主键</span><br><span class="line">alter table sicimike add primary key(id);</span><br><span class="line"></span><br><span class="line"># 删除主键</span><br><span class="line">alter table sicimike drop primary key;</span><br><span class="line"></span><br><span class="line"># 设置唯一键</span><br><span class="line">alter table sicimike add unique key(column_name);</span><br><span class="line"></span><br><span class="line"># 删除唯一键</span><br><span class="line">alter table sicimike drop index column_name;</span><br><span class="line"></span><br><span class="line"># 创建索引</span><br><span class="line">alter table sicimike add [unique&#x2F;fulltext&#x2F;spatial] index&#x2F;key index_name (identity_card[(len)] [asc&#x2F;desc])[using btree&#x2F;hash]</span><br><span class="line">create [unique&#x2F;fulltext&#x2F;spatial] index index_name on sicimike(identity_card[(len)] [asc&#x2F;desc])[using btree&#x2F;hash]</span><br><span class="line">example： alter table sicimike add index idx_na(name, age);</span><br><span class="line"></span><br><span class="line"># 删除索引</span><br><span class="line">alter table sicimike drop key&#x2F;index identity_card;</span><br><span class="line">drop index index_name on sicimike;</span><br><span class="line"></span><br><span class="line"># 查看索引</span><br><span class="line">show index from sicimike;</span><br><span class="line"></span><br><span class="line"># 查看列</span><br><span class="line">desc sicimike;</span><br><span class="line"></span><br><span class="line"># 新增列</span><br><span class="line">alter table sicimike add column column_name varchar(30);</span><br><span class="line"></span><br><span class="line"># 删除列</span><br><span class="line">alter table sicimike drop column column_name;</span><br><span class="line"></span><br><span class="line"># 修改列名</span><br><span class="line">alter table sicimike change column_name new_name varchar(30);</span><br><span class="line"></span><br><span class="line"># 修改列属性</span><br><span class="line">alter table sicimike modify column_name varchar(22);</span><br><span class="line"></span><br><span class="line"># 查看建表信息</span><br><span class="line">show create table sicimike;</span><br><span class="line"></span><br><span class="line"># 添加表注释</span><br><span class="line">alter table sicimike comment &#39;表注释&#39;;</span><br><span class="line"></span><br><span class="line"># 添加字段注释</span><br><span class="line">alter table sicimike modify column column_name varchar(10) comment &#39;姓名&#39;;</span><br></pre></td></tr></table></figure>

<h3 id="DML"><a href="#DML" class="headerlink" title="DML"></a>DML</h3><p>DML是数据操纵语言（Data Manipulation Language）的简称，包括最常见的SQL语句，例如<code>SELECT</code>，<code>INSERT</code>，<code>UPDATE</code>，<code>DELETE</code>等，它用于存储，修改，检索和删除数据库中的数据。</p>
<p>分页</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">-- 查询从第11条数据开始的连续5条数据</span><br><span class="line">select * from sicimike limit 10, 5</span><br><span class="line">group by</span><br></pre></td></tr></table></figure>

<p>默认情况下，MySQL中的分组（<code>group by</code>）语句，不要求<code>select</code>返回的列，必须是分组的列或者是一个聚合函数。</p>
<p>如果<code>select</code>查询的列不是分组的列，也不是聚合函数，则会返回该分组中第一条记录的数据。对比下面两条SQL语句，第二条SQL语句中，<code>cname</code>既不是分组的列，也不是以聚合函数的形式出现。所以在<code>liming</code>这个分组中，<code>cname</code>取的是第一条数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select * from c;</span><br><span class="line">+-----+-------+----------+</span><br><span class="line">| CNO | CNAME | CTEACHER |</span><br><span class="line">+-----+-------+----------+</span><br><span class="line">|   1 | 数学  | liming   |</span><br><span class="line">|   2 | 语文  | liming   |</span><br><span class="line">|   3 | 历史  | xueyou   |</span><br><span class="line">|   4 | 物理  | guorong  |</span><br><span class="line">|   5 | 化学  | liming   |</span><br><span class="line">+-----+-------+----------+</span><br><span class="line">5 rows in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select cteacher, count(cteacher), cname from c group by cteacher;</span><br><span class="line">+----------+-----------------+-------+</span><br><span class="line">| cteacher | count(cteacher) | cname |</span><br><span class="line">+----------+-----------------+-------+</span><br><span class="line">| guorong  |               1 | 物理  |</span><br><span class="line">| liming   |               3 | 数学  |</span><br><span class="line">| xueyou   |               1 | 历史  |</span><br><span class="line">+----------+-----------------+-------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br><span class="line">having</span><br></pre></td></tr></table></figure>

<p><code>having</code>关键字用于对分组后的数据进行筛选，功能相当于分组之前的<code>where</code>，不过要求更严格。过滤条件要么是一个聚合函数( <code>... having count(x) &gt; 1</code>)，要么是出现在select后面的列(<code>select col1, col2 ... group by x having col1 &gt; 1</code>)</p>
<p>多表更新</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">update tableA a inner join tableB b on a.xxx &#x3D; b.xxx set a.col1 &#x3D; xxx, b.col1 &#x3D; xxx where ...</span><br></pre></td></tr></table></figure>

<p>多表删除</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">delete a, b from tableA a inner join tableB b on a.xxx &#x3D; b.xxx where a.col1 &#x3D; xxx and b.col1 &#x3D; xxx</span><br></pre></td></tr></table></figure>

<h3 id="DCL"><a href="#DCL" class="headerlink" title="DCL"></a>DCL</h3><p>DCL是数据控制语言（Data Control Language）的简称，它包含诸如<code>GRANT</code>之类的命令，并且主要涉及数据库系统的权限，权限和其他控件。</p>
<ul>
<li><code>GRANT</code> ：允许用户访问数据库的权限</li>
<li><code>REVOKE</code>：撤消用户使用GRANT命令赋予的访问权限</li>
</ul>
<h3 id="TCL"><a href="#TCL" class="headerlink" title="TCL"></a>TCL</h3><p>TCL是事务控制语言（Transaction Control Language）的简称，用于处理数据库中的事务</p>
<ul>
<li><code>COMMIT</code>：提交事务</li>
<li><code>ROLLBACK</code>：在发生任何错误的情况下回滚事务</li>
</ul>
<h2 id="范式"><a href="#范式" class="headerlink" title="范式"></a>范式</h2><blockquote>
<p>数据库规范化，又称正规化、标准化，是数据库设计的一系列原理和技术，以减少数据库中数据冗余，增进数据的一致性。关系模型的发明者埃德加·科德最早提出这一概念，并于1970年代初定义了第一范式、第二范式和第三范式的概念，还与Raymond F. Boyce于1974年共同定义了第三范式的改进范式——BC范式。<br>除外还包括针对多值依赖的第四范式，连接依赖的第五范式、DK范式和第六范式。</p>
</blockquote>
<p>现在数据库设计最多满足3NF，普遍认为范式过高，虽然具有对数据关系更好的约束性，但也导致数据关系表增加而令数据库IO更易繁忙，原来交由数据库处理的关系约束现更多在数据库使用程序中完成。</p>
<h3 id="第一范式"><a href="#第一范式" class="headerlink" title="第一范式"></a>第一范式</h3><p>定义：数据库中的所有字段（列）都是单一属性，不可再分的。这个单一属性由基本的数据类型所构成，如整型、浮点型、字符串等。</p>
<p>第一范式是为了保证列的原子性。</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104430.webp" alt="img"></p>
<p>上表不满足第一范式，其中的地址列是可以再拆分的，可以拆分成省、市、区等</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104331.webp" alt="img"></p>
<h3 id="第二范式"><a href="#第二范式" class="headerlink" title="第二范式"></a>第二范式</h3><p>定义：数据库中的表不存在非关键字段对任一关键字字段的部分函数依赖</p>
<p>部分函数依赖是指存在着组合关键字中的某一关键字决定非关键字的情况</p>
<p>第二范式在满足了第一范式的基础上，消除非主键列对联合主键的部分依赖</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104402.webp" alt="img"></p>
<p>上面这张表中想要设置主键，只能是商品名称和供应商名称一起组成联合主键。但是价格和分类只依赖于商品名称，供应商电话只依赖于供应商名称，所以上面的表不满足第二范式，可以改成如下形式：</p>
<p>商品信息表</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104335.webp" alt="img"></p>
<p>供应商信息表</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104312.webp" alt="img"></p>
<p>商品-供应商关联表</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104428.webp" alt="img"></p>
<h3 id="第三范式"><a href="#第三范式" class="headerlink" title="第三范式"></a>第三范式</h3><p>定义：所有非主键属性都只和候选键有相关性，也就是说非主键属性之间应该是独立无关的。</p>
<p>第三范式是在满足了第二范式的基础上，消除列与列之间的传递依赖。</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104348.webp" alt="img"></p>
<p>在上面的表中，商品的分类描述依赖分类，而分类依赖商品名称，而不是分类描述直接依赖商品名称。这样就形成了传递依赖，所以不符合第三范式。可以改成如下形式</p>
<p>商品表</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104431.webp" alt="img"></p>
<p>商品分类表</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104311.webp" alt="img"></p>
<p>数据库设计时，遵循范式和反范式一直以来是一个颇受争议的问题。遵循范式对数据关系更好的约束性，并且减少数据冗余，可以更好地保证数据一致性。而反范式则是为了获得更好地性能。所以范式还是反范式并没有明确的标准，适合自己业务场景的才是最好的。</p>
<p>反范式设计时，需要考虑以下几个问题，分别是插入异常、更新异常和删除异常。</p>
<ul>
<li>插入异常：如果某个实体随着另一个实体的存在而存在，即缺少某个实体是无法表示这个实体，那么这个表就存在插入异常。</li>
<li>更新异常：如果更改表所对应的某个实体实例的单独属性时，需要将多行更新，那么就说明这个表存在更新异常</li>
<li>删除异常：如果删除表的某一行来表示某实体实例失效时，导致另一个不同实体实例信息丢失，那么这个表就存在删除异常</li>
</ul>
<p>以违反第二范式的表为例</p>
<p><img src="http://iubest.gitee.io/pic/640-1601002104427.webp" alt="img"></p>
<p>如果可乐第二制造厂这个供应商尚未开始供货，表中就不存在第二条记录，也就无法记录供应商的电话，这样就存在插入异常；如果需要把可乐的价格提高，需要更新表中的多条记录，这样就存在更新异常；如果删除可乐第二制造厂的供货信息，那么该供应商的电话也就丢失了，这样就存在删除异常。</p>
<p>一般存在插入异常的表，都会存在更新异常和删除异常。</p>
<h2 id="横表纵表"><a href="#横表纵表" class="headerlink" title="横表纵表"></a>横表纵表</h2><p>SQL脚本</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"># 横表</span><br><span class="line">CREATE TABLE &#96;table_h2z&#96; (</span><br><span class="line">&#96;name&#96; varchar(32) DEFAULT NULL,</span><br><span class="line">&#96;chinese&#96; int(11) DEFAULT NULL,</span><br><span class="line">&#96;math&#96; int(11) DEFAULT NULL,</span><br><span class="line">&#96;english&#96; int(11) DEFAULT NULL</span><br><span class="line">) ENGINE&#x3D;InnoDB AUTO_INCREMENT&#x3D;4 DEFAULT CHARSET&#x3D;utf8;</span><br><span class="line"></span><br><span class="line">&#x2F;*Data for the table &#96;table_h2z&#96; *&#x2F;</span><br><span class="line">insert  into &#96;table_h2z&#96;(&#96;name&#96;,&#96;chinese&#96;,&#96;math&#96;,&#96;english&#96;) values </span><br><span class="line">(&#39;mike&#39;,45,43,87),</span><br><span class="line">(&#39;lily&#39;,53,64,88),</span><br><span class="line">(&#39;lucy&#39;,57,75,75);</span><br><span class="line"></span><br><span class="line"># 纵表</span><br><span class="line">CREATE TABLE &#96;table_z2h&#96; (</span><br><span class="line">  &#96;name&#96; varchar(32) DEFAULT NULL,</span><br><span class="line">  &#96;subject&#96; varchar(8) NOT NULL DEFAULT &#39;&#39;,</span><br><span class="line">  &#96;score&#96; int(11) DEFAULT NULL</span><br><span class="line">) ENGINE&#x3D;InnoDB DEFAULT CHARSET&#x3D;utf8;</span><br><span class="line"></span><br><span class="line">&#x2F;*Data for the table &#96;table_z2h&#96; *&#x2F;</span><br><span class="line">insert  into &#96;table_z2h&#96;(&#96;name&#96;,&#96;subject&#96;,&#96;score&#96;) values </span><br><span class="line">(&#39;mike&#39;,&#39;chinese&#39;,45),</span><br><span class="line">(&#39;lily&#39;,&#39;chinese&#39;,53),</span><br><span class="line">(&#39;lucy&#39;,&#39;chinese&#39;,57),</span><br><span class="line">(&#39;mike&#39;,&#39;math&#39;,43),</span><br><span class="line">(&#39;lily&#39;,&#39;math&#39;,64),</span><br><span class="line">(&#39;lucy&#39;,&#39;math&#39;,75),</span><br><span class="line">(&#39;mike&#39;,&#39;english&#39;,87),</span><br><span class="line">(&#39;lily&#39;,&#39;english&#39;,88),</span><br><span class="line">(&#39;lucy&#39;,&#39;english&#39;,75);</span><br></pre></td></tr></table></figure>

<h3 id="横表转纵表"><a href="#横表转纵表" class="headerlink" title="横表转纵表"></a>横表转纵表</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT NAME, &#39;chinese&#39; AS &#96;subject&#96;,  chinese AS &#96;score&#96; FROM table_h2z</span><br><span class="line">UNION ALL</span><br><span class="line">SELECT NAME, &#39;math&#39; AS &#96;subject&#96;,  math AS &#96;score&#96; FROM table_h2z</span><br><span class="line">UNION ALL</span><br><span class="line">SELECT NAME, &#39;english&#39; AS &#96;subject&#96;, english AS &#96;score&#96; FROM table_h2z</span><br></pre></td></tr></table></figure>

<p>执行结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">+------+---------+-------+</span><br><span class="line">| name | subject | score |</span><br><span class="line">+------+---------+-------+</span><br><span class="line">| mike | chinese |    45 |</span><br><span class="line">| lily | chinese |    53 |</span><br><span class="line">| lucy | chinese |    57 |</span><br><span class="line">| mike | math    |    43 |</span><br><span class="line">| lily | math    |    64 |</span><br><span class="line">| lucy | math    |    75 |</span><br><span class="line">| mike | english |    87 |</span><br><span class="line">| lily | english |    88 |</span><br><span class="line">| lucy | english |    75 |</span><br><span class="line">+------+---------+-------+</span><br><span class="line">9 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>

<h3 id="纵表转横表"><a href="#纵表转横表" class="headerlink" title="纵表转横表"></a>纵表转横表</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT NAME,</span><br><span class="line"> SUM(CASE &#96;subject&#96; WHEN &#39;chinese&#39; THEN score ELSE 0 END) AS chinese,</span><br><span class="line"> SUM(CASE &#96;subject&#96; WHEN &#39;math&#39; THEN score ELSE 0 END) AS math,</span><br><span class="line"> SUM(CASE &#96;subject&#96; WHEN &#39;english&#39; THEN score ELSE 0 END) AS english</span><br><span class="line">FROM table_z2h</span><br><span class="line">GROUP BY NAME</span><br></pre></td></tr></table></figure>

<p>执行结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+------+---------+------+---------+</span><br><span class="line">| name | chinese | math | english |</span><br><span class="line">+------+---------+------+---------+</span><br><span class="line">| lily |      53 |   64 |      88 |</span><br><span class="line">| lucy |      57 |   75 |      75 |</span><br><span class="line">| mike |      45 |   43 |      87 |</span><br><span class="line">+------+---------+------+---------+</span><br><span class="line">3 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>

<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://www.w3schools.in/mysql/ddl-dml-dcl/">https://www.w3schools.in/mysql/ddl-dml-dcl/</a></li>
</ul>
<p><strong>END</strong></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/mysql/%E9%9B%B6%E6%95%A3%E7%9A%84MySQL%E5%9F%BA%E7%A1%80%E6%80%BB%E6%98%AF%E8%AE%B0%E4%B8%8D%E4%BD%8F%EF%BC%9F%E7%9C%8B%E8%BF%99%E4%B8%80%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mysql/" rel="tag">mysql</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/mysql/%E7%A5%9E%E5%A5%87%E7%9A%84%20SQL%EF%BC%8CGroup%20By/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            神奇的 SQL，Group By.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/oa/Python%E5%AE%9E%E7%8E%B0%E6%95%B0%E6%8D%AE%E5%86%99%E5%85%A5%20Excel%20%E7%9A%84%E4%B8%89%E7%A7%8D%E6%A8%A1%E5%9D%97/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Python实现数据写入 Excel 的三种模块.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>